package com.wb.utils;

import org.apache.commons.configuration.ConfigurationUtils;
import org.apache.commons.configuration.FileSystem;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 文件操作类
 * @author wb
 * @email 996649855@qq.com
 * @date 2021-10-21 20:38:01
 */
public class FileUtils {
    /**获取文件夹下所有文件的文件名*/
    public static List<String> getFilesName(String path){
        ArrayList<String> stringArrayList = new ArrayList<String>();

        File file = new File(path);
        if (file.exists()){
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    addFilesName(f,stringArrayList,path);
                }
            }else {
                String s = path.substring(path.lastIndexOf("template\\")) +"/"+ file.getName();
                stringArrayList.add(s.replace("\\","/"));
            }
        }
        return stringArrayList;
    }

    public static  void addFilesName(File file, List<String> list, String path){
        if (file.exists()){
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    addFilesName(f,list, path);
                }
            }else{
                String s = path.substring(path.lastIndexOf("template\\")) +"/"+ file.getName();
                list.add(s.replace("\\","/"));
            }
        }
    }

    public static String  getTemplatePath(String childPathName) {
        if (StringUtils.isBlank(childPathName)){
            throw new IllegalArgumentException("子文件名称不能为空");
        }
        URL findFile = ConfigurationUtils.locate(FileSystem.getDefaultFileSystem(), null, "generator.properties");
        String path = findFile.getPath();
        String rPath = path.replace("generator.properties", "template/"+childPathName);
        rPath = rPath.substring(1).replace("/", "\\");
        rPath = URLDecoder.decode(rPath);
        return rPath;
    }
}
